package com.zihuop.server

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import android.os.Bundle
import android.os.IBinder
import android.os.RemoteException
import android.util.Log
import android.view.View
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import com.zihuop.server.service.RemoteService

class MainActivity : AppCompatActivity() {
    private lateinit var text: TextView;
    private val TAG = MainActivity::class.java.simpleName
    private lateinit var mConnection: ServiceConnection
    private lateinit var mProcessInfo: IProcessInfo

    private val operationListener: IOperationListener = object : IOperationListener.Stub() {

        override fun onOperation(test: Test?) {
            runOnUiThread { "运算结果:${test.toString()}".also { text.text = it } }
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        text = findViewById<TextView>(R.id.tv_bind_status)

        mConnection = object : ServiceConnection {
            override fun onServiceConnected(componentName: ComponentName, iBinder: IBinder) {
                Log.i(TAG, "RemoteService onServiceConnected")
                mProcessInfo = IProcessInfo.Stub.asInterface(iBinder)
                runOnUiThread { text.text = "本地服务绑定成功" }
            }

            override fun onServiceDisconnected(componentName: ComponentName) {
                Log.i(TAG, "RemoteService onServiceDisconnected")
            }
        }
    }

    fun bindLocalService(view: View) {
        val intent: Intent = Intent(this, RemoteService::class.java)
        val result = bindService(intent, mConnection, Context.BIND_AUTO_CREATE)
        Log.d(TAG, "bindLocalService 结果：$result")
    }

    fun registerService(view: View) {
        mProcessInfo.registerListener(operationListener)
        runOnUiThread { text.text = "本地服务注册完成" }
    }

    fun unregisterService(view: View) {
        mProcessInfo.unregisterListener(operationListener)
        runOnUiThread { text.text = "本地服务注销完成" }
    }

    fun operationService(view: View) {
        try {
            Log.i(TAG, "aidl调用 " + mProcessInfo.operation(Test(89, "1212")))
        } catch (e: RemoteException) {
            e.printStackTrace()
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        unbindService(mConnection)
    }
}